package org.tio.sitexxx.web.server.controller.tiosite;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.server.annotation.RequestPath;
import org.tio.http.server.util.Resps;
import org.tio.sitexxx.service.model.main.IpInfo;
import org.tio.sitexxx.service.model.stat.AdStat;
import org.tio.sitexxx.service.service.base.IpInfoService;
import org.tio.sitexxx.service.service.tiosite.AdService;
import org.tio.sitexxx.service.service.tiosite.stat.AdStatService;
import org.tio.sitexxx.web.server.utils.WebUtils;
import org.tio.utils.resp.Resp;

import com.jfinal.plugin.activerecord.Record;

/**
 * @author tanyaowu
 * 2016年7月22日 上午10:44:13
 */
@RequestPath(value = AdController.BEAN_PATH)
public class AdController {
	public static final String BEAN_PATH = "/ad";

	private static Logger log = LoggerFactory.getLogger(AdController.class);

	static final AdService srv = AdService.me;

	/**
	 *
	 * @author tanyaowu
	 */
	public AdController() {
	}

	/**
	 * 
	 * @param adid
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestPath(value = "/{adid}", forward = BEAN_PATH + "/redirect")
	public HttpResponse redirect(Integer adid, HttpRequest request) throws Exception {
		if (adid == null) {
			request.close();
			return null;
		}

		Record record = srv.getById(adid);
		if (record == null) {
			request.close();
			return null;
		}

		String url = record.get("url");

		if (StringUtils.startsWith(url, "http://") || StringUtils.startsWith(url, "https://")) {

		} else {
			url = "https://127.0.0.1:444" + WebUtils.path(url);
		}
		String ip = request.getClientIp();
		AdStat adStat = new AdStat();
		adStat.setReferer(request.getReferer());
		adStat.setAdId(adid);
		adStat.setIp(ip);
		adStat.setAdUrl(url);
		adStat.setUserAgent(StringUtils.left(request.getUserAgent(), 1024));
		adStat.setSessionid(request.getHttpSession().getId());

		IpInfo ipInfo = IpInfoService.ME.save(ip);
		adStat.setIpid(ipInfo.getId());
		adStat.setTime(new Date());
		adStat.setType((byte) 1);

		AdStatService.me.save(adStat);

		//		String encodeurl = URLEncoder.encode(url, request.getCharset());
		String bodystr = "<script>window.location.href='" + url + "';</script>";
		//		String bodystr = "<script>window.location.href='/api/ad/redirectTest.php';</script>";
		return Resps.html(request, bodystr);
		//		return Resps.redirect(request, url);

	}

	@RequestPath(value = "/redirectTest")
	public Resp redirectTest(HttpRequest request) throws Exception {
		log.warn(request.toString());
		return Resp.ok();
	}

	/**
	 * 首页广告
	 * @return
	 * @author tanyaowu
	 */
	@RequestPath(value = "/homepage")
	public Resp homepage() {
		return Resp.ok(AdService.me.queryHomepage());
	}

}
